package com.headerfooter.songhang.library;

import ohos.agp.components.*;

/**
 * Created by songhang on 16/4/25.
 */
public class SmartRecyclerAdapter extends RecyclerViewAdapterWrapper {
    /**
     * header标识
     */
    public static final int TYPE_HEADER = -1;

    /**
     * footer标识
     */
    public static final int TYPE_FOOTER = -2;

    private Component headerView;
    private Component footerView;

    /**
     * 构造方法
     *
     * @param targetAdapter provider参数
     */
    public SmartRecyclerAdapter(BaseItemProvider targetAdapter) {
        super(targetAdapter);
    }

    /**
     * 设置headerview
     *
     * @param view component参数
     */
    public void setHeaderView(Component view) {
        headerView = view;
        getWrappedAdapter().notifyDataChanged();
    }

    /**
     * 移除headerview
     */
    public void removeHeaderView() {
        headerView = null;
        getWrappedAdapter().notifyDataChanged();
    }

    /**
     * 设置footerview
     * @param view component参数
     */
    public void setFooterView(Component view) {
        footerView = view;
        getWrappedAdapter().notifyDataChanged();
    }

    /**
     * 移除footerview
     */
    public void removeFooterView() {
        footerView = null;
        getWrappedAdapter().notifyDataChanged();
    }

    private boolean hasHeader() {
        return headerView != null;
    }

    private boolean hasFooter() {
        return footerView != null;
    }

    @Override
    public int getCount() {
        return super.getCount() + (hasHeader() ? 1 : 0) + (hasFooter() ? 1 : 0);
    }

    @Override
    public Object getItem(int position) {
        return wrapped.getItem(position);
    }

    @Override
    public long getItemId(int position) {
        return wrapped.getItemId(position);
    }

    @Override
    public int getItemComponentType(int position) {
        if (hasHeader() && position == 0) {
            return TYPE_HEADER;
        }

        if (hasFooter() && position == getCount() - 1) {
            return TYPE_FOOTER;
        }
        return super.getItemComponentType(hasHeader() ? position - 1 : position);
    }

    @Override
    public Component getComponent(int index, Component component, ComponentContainer componentContainer) {
        Component itemView = null;

        if (getItemComponentType(index) == TYPE_HEADER) {
            itemView = headerView;
            return itemView;
        }

        if (getItemComponentType(index) == TYPE_FOOTER) {
            itemView = footerView;
            return itemView;
        }

        itemView = super.getComponent(index - 1, component, componentContainer);
        return itemView;
    }
}
